using System;
using System.Collections.Generic;
using System.Text;
using Rapier.Kodachi.Shared;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;
using System.Drawing;

namespace Rapier.Kodachi.Core.Actions
{
    public class Launch : Action
    {
        #region Constructor
        public Launch(Plugin plugin)
            : base(plugin, "Rapier.CorePlugin.Launch", "Launch", "Launches the item with the Windows shell.")
        {
            string systemPath = System.Environment.GetFolderPath(Environment.SpecialFolder.System);
            string itemPath = systemPath.Substring(0, systemPath.LastIndexOf('\\')) + @"\explorer.exe";
            GetImage = delegate() { return CoreCatalog.GetImageFromPath(itemPath); };
        }
        #endregion

        #region Action Members
        public override bool IsValidDirect(Item directItem)
        {
            return directItem.Properties.ContainsKey("Path") || directItem.Properties.ContainsKey("ShellCommand");
        }

        public override void Execute(Item[] directItems, Item[] indirectItems)
        {
            foreach (Item directItem in directItems)
            {
                string command = String.Empty;
                if (directItem.Properties.ContainsKey("ShellCommand"))
                    command = directItem.Properties["ShellCommand"].ToString();
                else
                    command = directItem.Properties["Path"].ToString();

                 string arguments = String.Empty;
                 if( directItem.Properties.ContainsKey( "Arguments" ) )
                    arguments = directItem.Properties["Arguments"].ToString();
                ProcessStartInfo psi = new ProcessStartInfo(command, arguments);
                psi.UseShellExecute = true;
                if (directItem.Properties.ContainsKey("WorkingDirectory"))
                    psi.WorkingDirectory = directItem.Properties["WorkingDirectory"].ToString();
                else if (directItem.Properties.ContainsKey("Path"))
                    psi.WorkingDirectory = Path.GetDirectoryName(directItem.Properties["Path"].ToString());

                Process.Start(psi);
            }
        }
        #endregion
    }
}
